package pract1modif;


public class ThreadUtility {
  
  /**
   * This method shows the active threads, debug purposes
   */
  public void showActiveThreads() {
    // Find the root thread group
    ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
    while (root.getParent() != null) {
        root = root.getParent();
    }
    this.visit(root, 0);
  }
 
  /**
   *This method recursively visits all thread groups under `group''.
   */
  public void visit(ThreadGroup group, int level) {
    // Obtain the threads of the group
    int numThreads = group.activeCount();
    Thread[] threads = new Thread[numThreads * 2];
    numThreads = group.enumerate(threads, false);

    // print each thread name in the group
    for (int i = 0; i < numThreads; i++ ) {
      // Get thread
      Thread thread = threads[i];
      System.out.println("Thread Name: " + thread.getName());
    }

    // Get thread subgroups of group
    int numGroups = group.activeGroupCount();
    ThreadGroup[] groups = new ThreadGroup[numGroups * 2];
    numGroups = group.enumerate(groups, false);

    // Recursively visit each subgroup
    for (int i = 0; i < numGroups; i++ ) {
      this.visit(groups[i],1);
    }
  }
}
